package edu.vt.ece_3574.amber_alert;


import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import edu.vt.ece_3574.amber_alert.AlertSettings.PollingInterval;
import edu.vt.ece_3574.amber_alert.accounts.Account;
import edu.vt.ece_3574.amber_alert.database.DatabaseHandler;
import edu.vt.ece_3574.amber_alert.membership.AccountCreationActivity;

public class LoginActivity extends Activity {
	EditText userNameField = null;
	EditText passwordField = null;
	
	Button loginButton;
	Button createAccountButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		createAccountButton = (Button) findViewById(R.id.createAccountButton);
		loginButton = (Button)findViewById(R.id.loginbutton);
		userNameField = (EditText)findViewById(R.id.username);
		passwordField = (EditText)findViewById(R.id.password);
		
		checkInternetConnection();
		
		ensureC2DMRegistered();
		
		Account rememberedAccount = getRememberedAccount();
		if (rememberedAccount != null) {
			AmberAlertApplication.get().setCurrentAccount(rememberedAccount);
			if (rememberedAccount.getType().equals("Primary")) {
				Intent i = new Intent(LoginActivity.this, PrimaryMain.class);
				startActivity(i);
			}
			else if (rememberedAccount.getType().equals("Member")) {
				Intent i = new Intent(LoginActivity.this, MemberMain.class);
				startActivity(i);
			}
		}
		
		createAccountButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(LoginActivity.this, AccountCreationActivity.class);
				LoginActivity.this.finish();
				startActivity(i);
			}
		});
		
		SharedPreferences settings = getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("interval", Integer.toString(PollingInterval.defaultInterval));
		editor.commit();
		
		loginButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				String result = checkCredentials();
				if(result.equals("Success")) {
					Account currentAccount = AmberAlertApplication.get().getCurrentAccount();
					
					CheckBox rememberMeCheckbox = (CheckBox) findViewById(R.id.checkRemember);
					if (rememberMeCheckbox.isChecked()) {
						setRememberedAccount(userNameField.getText().toString());
					}
					
					String c2dmId = getC2DMIDForPhone();
					if (!c2dmId.equals("NotSet")) {
						currentAccount.setSerialNumber(c2dmId);
					}
					
					if (currentAccount.getType().equals("Primary")) {
						Intent i = new Intent(LoginActivity.this, PrimaryMain.class);
						startActivity(i);
						LoginActivity.this.finish();
					}
					else if (currentAccount.getType().equals("Member")) {
						Intent i = new Intent(LoginActivity.this, MemberMain.class);
						startActivity(i);
						LoginActivity.this.finish();
					}
				}
				else {
					showFailureMessage(result);
				}
			}			
		});
	}
	
	private void ensureC2DMRegistered() {
		SharedPreferences settings = getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
		boolean c2dmRegistered = settings.getBoolean("c2dmRegisteredAmberAlert", false);
		if (!c2dmRegistered) {
			Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
			intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0));
			intent.putExtra("sender", "accorvin@gmail.com");
			startService(intent);
		}
		
	}

	/**
	 * Checks whether the password matches the supplied username
	 * @return whether the username and password match
	 */
	private String checkCredentials(){
		String userNameError = "Username field empty!";
		String passwordError = "Password field empty!";
		String errorMessage = "Wrong username or password.";
		String noUserExistsError = "No user by that name exists.";
		
		String userNameString = userNameField.getText().toString();
		String passwordString = passwordField.getText().toString();
		
		if(userNameField.length() == 0)
			return userNameError;
		else if(passwordField.length() == 0)
			return passwordError;
		else if (!DatabaseHandler.get().determineIfUserExistsOnServer(userNameString)) {
			return noUserExistsError;
		}
		
		Account loginAccount = DatabaseHandler.get().checkLoginCredentials(userNameString, passwordString);
		if (loginAccount == null) {
			return errorMessage;
		}
		else {
			AmberAlertApplication.get().setCurrentAccount(loginAccount);
			return "Success";
		}
	}
	

	/**
	 * Shows a failure message if the login information was incorrect
	 * @param string of error message to be displayed
	 */
	private void showFailureMessage(String errorMessage) {
		Context context = getApplicationContext();
		CharSequence message = errorMessage;
		int duration = Toast.LENGTH_LONG;

		Toast toast = Toast.makeText(context, message, duration);
		toast.setGravity(Gravity.CENTER | Gravity.FILL_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	private Account getRememberedAccount() {
		Account rememberedAccount = null;
		SharedPreferences settings = getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
		String rememberedAccountString = settings.getString("rememberedAccountName", "AmberAlertAccountNotSet");
		if ((!rememberedAccountString.equals("AmberAlertAccountNotSet")) && (DatabaseHandler.get().determineIfUserExistsOnServer(rememberedAccountString))) {
			rememberedAccount = DatabaseHandler.get().getAccountFromServerByName(rememberedAccountString);
		}
		return rememberedAccount;
	}
	
	private void setRememberedAccount(String accountName) {
		SharedPreferences settings = getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("rememberedAccountName", accountName);
		editor.commit();
	}
	
	
	public String getC2DMIDForPhone() {
		SharedPreferences settings = getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
		return settings.getString("c2dmRegistrationID", "NotSet");
	}
	
	private void checkInternetConnection() {
		if (!DatabaseHandler.get().checkForInternetConnection()) {
			loginButton.setEnabled(false);
			createAccountButton.setEnabled(false);
			showFailureMessage("No internet connection found.");
		}
		else {
			loginButton.setEnabled(true);
			createAccountButton.setEnabled(true);
		}
	}
}
